<?php

/**
 * 用户支付信息表
 */

use Common\Bridge;
use lib\core\AdminAction;
use Passport\User as PUser;
use Center\User as CUser;
use Center\Payment;
use Center\UserRelationship;
use Center\CashLog;

define('SITE_AUTH', 'user-order-line');
require('../../../common.inc.php');

class userOrder extends AdminAction
{
    private $pdo_r;

    private $field = [
        'PaymentId' => '订单ID',
        'UserId' => '用户ID',
        'SN' => '支付流水号,自己生成',
        'ProductId' => ['Title' => '商品', 'Data' => [1 => '美特体脂称']],
        'PaymentType' => ['Title' => '支付平台', 'Data' => [1 => '微信']],
        'TradeNo' => '交易号',
        'TotalFee' => '支付金额',
        'Status' => [
            'Title' => '支付状态',
            'Data' => [0 => '等待支付', 1 => '支付中', 2 => '支付成功', 3 => '支付失败', 4 => '取消支付', 5 => '奖励成功']
        ],
        'UpdateTime' => '最后状态更新时间',
        'CreateTime' => '创建时间'
    ];

    private $primary_key = 'PaymentId';

    const TABLE_NAME = 'Payment';

    public function doDefault()
    {
        $param['UserId'] = (int)$_GET['UserId'];
        $param['Mobile'] = trim($_GET['Mobile']);

        //交易号
        $param['TradeNo'] = $_GET['TradeNo'];
        $param['Status'] = trim($_GET['Status']);

        $field = $this->field;
        $field_key = array_keys($field);
        $field_key_str = '`' . implode('`,`', $field_key) . '`';

        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "1";

        if (!empty($param['Mobile'])) {
            $uid = PUser::checkMobile($param['Mobile']);
            if ($uid < 1) {
                HDshowMsg('操作失败！', ['type' => 'error', 'desc' => "电话号码为" . $param['Mobile'] . "用户不存在"]);
            }

            $where .= " AND UserId = " . $uid;
        } elseif ($param['UserId'] > 0) {
            $where .= " AND UserId = " . $param['UserId'];
        } else {
            $param['UserId'] = '';
        }

        if ($param['TradeNo']) {
            $where .= " AND TradeNo = '" . $param['TradeNo'] . "'";
        }
        if ($param['Status'] !== '') {
            $param['Status'] = intval($param['Status']);
            $where .= " AND Status = '" . $param['Status'] . "'";
        }

        $primary_key = $this->primary_key;
        if (!empty($_GET['exportExcel'])) {
            $sql = "SELECT $field_key_str FROM `" . self::TABLE_NAME . "` WHERE $where ORDER BY $primary_key DESC";
            $data = $this->readDb($sql);
            $user = $user_id = [];
            foreach ($data as $k => $v) {
                $data[$k]['TotalFee'] = sprintf('%.2f', $v['TotalFee'] / 100);
                $user_id[$v['UserId']] = $v['UserId'];
            }
            set_time_limit(0);
            if (!empty($user_id)) {
                $user_data = CUser::getDataListByIds($user_id);
                foreach ($user_data as $k => $v) {
                    $user[$v['UserId']] = $v['NickName'];
                }
            }
            $filename = mb_convert_encoding('商品订单-' . date("YmdHis"), "GB2312", "UTF-8");
            $filename_type = 'xls';
            header("Content-type:application/vnd.ms-excel");
            Header("Accept-Ranges:bytes");
            Header("Content-Disposition:attachment;filename=" . $filename . "." . $filename_type);  //$filename导出的文件名
            header("Pragma: no-cache");
            header("Expires: 0");
            $excel_str = '';
            if ($filename_type == 'xls') {
                $excel_str = <<<EOT
            <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
             <head>
              <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
              <meta http-equiv=Content-Type content="text/html; charset=gb2312">
              <!--[if gte mso 9]><xml>
              <x:ExcelWorkbook>
              <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                <x:Name></x:Name>
                <x:WorksheetOptions>
                  <x:DisplayGridlines/>
                </x:WorksheetOptions>
                </x:ExcelWorksheet>
              </x:ExcelWorksheets>
              </x:ExcelWorkbook>
              </xml><![endif]-->
             </head>
EOT;
            }
            $excel_str .= '<table>';
            $excel_str .= '<tr><td>订单ID</td><td>用户ID</td><td>昵称</td><td>支付流水号</td><td>交易号</td><td>支付金额(元)</td><td>支付状态</td><td>更新时间</td><td>创建时间</td></tr>';
            foreach ($data as $k => $v) {
                $excel_str .= "<tr><td style='vnd.ms-excel.numberformat:@'>{$v['PaymentId']}</td><td style='vnd.ms-excel.numberformat:@'>{$v['UserId']}</td><td>{$user[$v['UserId']]}</td><td style='vnd.ms-excel.numberformat:@'>{$v['SN']}</td><td>{$v['TradeNo']}</td><td>{$v['TotalFee']}</td><td>{$field['Status']['Data'][$v['Status']]}</td><td>{$v['UpdateTime']}</td><td>{$v['CreateTime']}</td></tr>";
            }
            $excel_str .= '</table>';
            echo mb_convert_encoding($excel_str,"GB2312","UTF-8");
            exit();
        }
        $count_sql = "SELECT COUNT($primary_key) AS `num` FROM `" . self::TABLE_NAME . "` WHERE $where";
        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $sql = "SELECT $field_key_str FROM `" . self::TABLE_NAME . "` WHERE $where ORDER BY $primary_key DESC LIMIT $offset,$limit";
        $data = $this->readDb($sql);

        $smarty = $this->app->page();
        if ($count > 0) {
            if (!empty($data)) {
                $user_id = [];
                foreach ($data as $k => $v) {
                    if ($v['Status'] == 2) {
                        $data[$k]['disDay'] = floor((strtotime($v['UpdateTime']) - time()) / 86400);
                    } else {
                        $data[$k]['disDay'] = 0;
                    }
                    $data[$k]['TotalFee'] = sprintf('%.2f', $v['TotalFee'] / 100);
                    $user_id[$v['UserId']] = $v['UserId'];
                }
                $smarty->value('list', $data);
                $user_data = CUser::getDataListByIds($user_id);
                $user = [];
                foreach ($user_data as $k => $v) {
                    $user[$v['UserId']] = $v['NickName'];
                }

                $smarty->value('user', $user);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }


        $smarty->value('param', $param);
        $smarty->value('field', $field);
        $smarty->output('order/orderList.tpl');
    }

    /**
     * 发放邀请奖励
     */
    public function doInviteReward()
    {
        $id = intval($_POST['id']);
        $pay_info = Payment::getInfoByIds($id);
        if (empty($pay_info['UserId'])) {
            $this->output(['type' => 'error', 'msg' => '订单id错误']);
        }
        if ($pay_info['Status'] != Payment::STATUS_PAY_SUCCESS) {
            $this->output(['type' => 'error', 'msg' => '订单状态错误']);
        }
        $pusers = UserRelationship::getDataInfoById($pay_info['UserId']);
        if (!empty($pusers['InviteUserId'])) { // 一级邀请奖励
            $r = CashLog::inviteReward($pay_info['UserId'], $pusers['InviteUserId'], CashLog::TYPE_INVITE);
            if ($r) {
                $ppusers = UserRelationship::getDataInfoById($pusers['InviteUserId']);
                if (!empty($ppusers['InviteUserId'])) { // 二级邀请奖励
                    $r2 = CashLog::inviteReward($pay_info['UserId'], $ppusers['InviteUserId'],
                        CashLog::TYPE_SUB_INVITE);
                    if ($r2 === false) {
                        $log = [
                            'payid' => $pay_info['PaymentId'],
                            'uid' => $pay_info['UserId'],
                            'ppuid' => $ppusers['InviteUserId'],
                            'time' => date('Y-m-d H:i:s'),
                        ];
                        runtime_log('Wallet/invite_reward_err', $log);
                        Payment::update($pay_info['PaymentId'], ['Status' => Payment::STATUS_PAY_REWARD]);
                        $this->output(['type' => 'error', 'msg' => '发放二级邀请奖励失败']);
                    }
                }
            } else {
                $log = [
                    'payid' => $pay_info['PaymentId'],
                    'uid' => $pay_info['UserId'],
                    'puid' => $pusers['InviteUserId'],
                    'time' => date('Y-m-d H:i:s'),
                ];
                runtime_log('Wallet/invite_reward_err', $log);
                $this->output(['type' => 'error', 'msg' => '发放一级邀请奖励失败']);
            }
        }
        Payment::update($pay_info['PaymentId'], ['Status' => Payment::STATUS_PAY_REWARD]);
        $this->output(['type' => 'success', 'msg' => '邀请奖励发放成功']);
    }

    /**
     * 利用SQL语句读取数据库并返回相应数据
     *
     * @param $sql
     * @return mixed
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_R);
        }

        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }
}

$app->run();